package com.lipei.vrp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class Vrptest {

	public static void main(String[] args) {
		String vrppath = "J:\\SYMPHONY-5.2-Stable\\SYMPHONY\\Applications\\VRP\\MSVisualStudio\\v9\\Debug\\vrp.exe";

		DecimalFormat format = new DecimalFormat("0.000");
		String command = vrppath + " -F \""
				+ "C:\\Users\\lipei\\Desktop\\C1_10_30_3.vrp" + "\" -N 5";

		final ProcessBuilder builder = new ProcessBuilder(command);
		builder.redirectInput(Redirect.PIPE);

		try {
			final ArrayList<String> list = new ArrayList<String>();
			final Process pro = builder.start();

			Thread vrpthread = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						InputStream input = pro.getInputStream();

						BufferedReader reader = new BufferedReader(
								new InputStreamReader(input));
						while (true) {
							String readLine;

							readLine = reader.readLine();

							if (readLine == null) {
								break;
							}
							list.add(readLine);

							System.out.println(readLine);
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});

			boolean timeout = false;
			vrpthread.start();
			try {
				vrpthread.join(60000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}

			if (vrpthread.isAlive()) {
				timeout = true;
				pro.destroy();
			}
			if (!timeout && pro.exitValue() != 0) {
				throw new RuntimeException("vrp error, return is :"
						+ pro.exitValue());
			}

			ResultType resulttype = null;
			if (timeout) {
				resulttype = ResultType.OT;
			}
			for (String string : list) {
				if (string.contains("Optimal Solution Found")) {
					resulttype = ResultType.OPT;
					break;
				}
				if (string.contains("Branch and Cut Finished")) {
					resulttype = ResultType.NUL;
					break;
				}
				if (string.contains("Max num of cuts in CP pool exceeded")
						&& timeout) {
					resulttype = ResultType.MCOT;
				}
			}
			int i = list.size() - 1;
			for (; i >= 0; i--) {
				String line = list.get(i);
				if (line.contains("Solution Cost")) {
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("oyeah!");
	}

}
